<template>
	<view class="search-result-container">
		<!-- 自定义导航栏 -->
		<ob-navbar 
			title="搜索结果"
			:show-back="true"
			:background="'#FFFFFF'"
		/>
		
		<!-- 搜索信息栏 -->
		<view class="search-info">
			<text class="search-keyword">{{ searchKeyword }}</text>
			<text class="result-count">共找到{{ totalCount }}个商品</text>
		</view>
		
		<!-- 筛选和排序栏 -->
		<view class="filter-bar">
			<view class="filter-item" @click="showFilterModal = true">
				<text class="filter-text">筛选</text>
				<text class="filter-icon">🔽</text>
			</view>
			<view class="sort-item" @click="showSortModal = true">
				<text class="sort-text">{{ currentSort.label }}</text>
				<text class="sort-icon">🔽</text>
			</view>
		</view>
		
		<!-- 商品列表 -->
		<view class="product-list">
			<view 
				v-for="(product, index) in productList" 
				:key="product.id"
				class="product-item"
				@click="goToProductDetail(product.id)"
			>
				<ob-product-card
					:product="product"
					:layout="'list'"
					:show-add-cart="true"
					@add-cart="addToCart"
				/>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view v-if="productList.length === 0 && !isLoading" class="empty-state">
			<ob-empty 
				:image="'/static/images/empty-search.png'"
				title="没有找到相关商品"
				description="试试其他关键词吧"
			/>
		</view>
		
		<!-- 加载更多 -->
		<view v-if="hasMore" class="load-more" @click="loadMore">
			<text class="load-text">加载更多</text>
		</view>
		
		<!-- 筛选弹窗 -->
		<view v-if="showFilterModal" class="filter-modal" @click="showFilterModal = false">
			<view class="filter-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">筛选条件</text>
					<text class="modal-close" @click="showFilterModal = false">✕</text>
				</view>
				
				<view class="filter-section">
					<text class="section-title">价格区间</text>
					<view class="price-range">
						<input class="price-input" v-model="filterParams.minPrice" placeholder="最低价" type="number" />
						<text class="price-separator">-</text>
						<input class="price-input" v-model="filterParams.maxPrice" placeholder="最高价" type="number" />
					</view>
				</view>
				
				<view class="filter-section">
					<text class="section-title">商品分类</text>
					<view class="category-list">
						<view 
							v-for="category in categories" 
							:key="category.id"
							class="category-item"
							:class="{ active: filterParams.categoryId === category.id }"
							@click="selectCategory(category.id)"
						>
							<text class="category-name">{{ category.name }}</text>
						</view>
					</view>
				</view>
				
				<view class="modal-footer">
					<button class="reset-btn" @click="resetFilter">重置</button>
					<button class="confirm-btn" @click="applyFilter">确定</button>
				</view>
			</view>
		</view>
		
		<!-- 排序弹窗 -->
		<view v-if="showSortModal" class="sort-modal" @click="showSortModal = false">
			<view class="sort-content" @click.stop>
				<view 
					v-for="sort in sortOptions" 
					:key="sort.value"
					class="sort-option"
					:class="{ active: currentSort.value === sort.value }"
					@click="selectSort(sort)"
				>
					<text class="sort-label">{{ sort.label }}</text>
					<text v-if="currentSort.value === sort.value" class="sort-check">✓</text>
				</view>
			</view>
		</view>
		
		<ob-loading :visible="isLoading" text="搜索中..." />
	</view>
</template>

<script setup>
import { ref, computed, inject, onMounted } from 'vue'
import productApi from '../../api/product.js'

const store = inject('$store')

// 响应式数据
const searchKeyword = ref('')
const productList = ref([])
const totalCount = ref(0)
const currentPage = ref(1)
const hasMore = ref(true)
const isLoading = ref(false)
const showFilterModal = ref(false)
const showSortModal = ref(false)

const filterParams = ref({
	minPrice: '',
	maxPrice: '',
	categoryId: ''
})

const currentSort = ref({
	label: '综合排序',
	value: 'default'
})

const sortOptions = [
	{ label: '综合排序', value: 'default' },
	{ label: '价格从低到高', value: 'price_asc' },
	{ label: '价格从高到低', value: 'price_desc' },
	{ label: '销量优先', value: 'sales_desc' },
	{ label: '最新发布', value: 'create_time_desc' }
]

const categories = ref([
	{ id: 1, name: '船舶用品' },
	{ id: 2, name: '生活用品' },
	{ id: 3, name: '食品饮料' },
	{ id: 4, name: '电子设备' },
	{ id: 5, name: '服装鞋帽' }
])

// 页面初始化
onMounted(() => {
	initPageData()
	searchProducts()
})

const initPageData = () => {
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const options = currentPage.options
	
	searchKeyword.value = options.keyword || ''
}

const searchProducts = async (isLoadMore = false) => {
	try {
		if (!isLoadMore) {
			isLoading.value = true
			currentPage.value = 1
		}
		
		const params = {
			keyword: searchKeyword.value,
			page: currentPage.value,
			limit: 20,
			sortBy: currentSort.value.value,
			...filterParams.value
		}
		
		const response = await productApi.searchProducts(params)
		
		if (isLoadMore) {
			productList.value = [...productList.value, ...response.list]
		} else {
			productList.value = response.list || []
		}
		
		totalCount.value = response.total || 0
		hasMore.value = response.hasMore || false
		
	} catch (error) {
		console.error('搜索商品失败:', error)
		uni.showToast({
			title: '搜索失败',
			icon: 'none'
		})
	} finally {
		isLoading.value = false
	}
}

// 加载更多
const loadMore = () => {
	if (hasMore.value && !isLoading.value) {
		currentPage.value++
		searchProducts(true)
	}
}

// 筛选相关
const selectCategory = (categoryId) => {
	filterParams.value.categoryId = filterParams.value.categoryId === categoryId ? '' : categoryId
}

const resetFilter = () => {
	filterParams.value = {
		minPrice: '',
		maxPrice: '',
		categoryId: ''
	}
}

const applyFilter = () => {
	showFilterModal.value = false
	searchProducts()
}

// 排序相关
const selectSort = (sort) => {
	currentSort.value = sort
	showSortModal.value = false
	searchProducts()
}

// 页面跳转
const goToProductDetail = (productId) => {
	uni.navigateTo({
		url: `/pages/product/detail?id=${productId}`
	})
}

// 购物车操作
const addToCart = (product) => {
	store.actions.addToCart({
		productId: product.id,
		quantity: 1,
		specs: product.defaultSpecs || {}
	})
	
	uni.showToast({
		title: '已添加到购物车',
		icon: 'success'
	})
}
</script>

<style lang="scss" scoped>
.search-result-container {
	background: #F5F5F5;
	min-height: 100vh;
}

.search-info {
	background: #FFFFFF;
	padding: 15px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	border-bottom: 1px solid #F0F0F0;
	
	.search-keyword {
		font-size: 16px;
		font-weight: 600;
		color: var(--primary-color);
		
		&::before {
			content: '"';
		}
		
		&::after {
			content: '"';
		}
	}
	
	.result-count {
		font-size: 14px;
		color: #666666;
	}
}

.filter-bar {
	background: #FFFFFF;
	padding: 12px 15px;
	display: flex;
	align-items: center;
	border-bottom: 1px solid #F0F0F0;
	margin-bottom: 10px;
	
	.filter-item,
	.sort-item {
		display: flex;
		align-items: center;
		gap: 4px;
		padding: 6px 12px;
		background: #F8F9FA;
		border-radius: 15px;
		margin-right: 12px;
		
		.filter-text,
		.sort-text {
			font-size: 14px;
			color: #333333;
		}
		
		.filter-icon,
		.sort-icon {
			font-size: 10px;
			color: #666666;
		}
	}
}

.product-list {
	padding: 0 15px;
}

.product-item {
	margin-bottom: 10px;
}

.empty-state {
	padding: 50px 20px;
}

.load-more {
	padding: 20px;
	text-align: center;
	
	.load-text {
		color: var(--primary-color);
		font-size: 14px;
	}
}

.filter-modal,
.sort-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 1000;
	display: flex;
	align-items: flex-end;
}

.filter-content {
	background: #FFFFFF;
	border-radius: 12px 12px 0 0;
	width: 100%;
	max-height: 70vh;
	overflow-y: auto;
}

.modal-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px;
	border-bottom: 1px solid #F0F0F0;
	
	.modal-title {
		font-size: 18px;
		font-weight: 600;
		color: #333333;
	}
	
	.modal-close {
		font-size: 18px;
		color: #999999;
	}
}

.filter-section {
	padding: 20px;
	border-bottom: 1px solid #F0F0F0;
	
	.section-title {
		font-size: 16px;
		font-weight: 600;
		color: #333333;
		margin-bottom: 15px;
		display: block;
	}
}

.price-range {
	display: flex;
	align-items: center;
	gap: 10px;
	
	.price-input {
		flex: 1;
		height: 40px;
		padding: 0 12px;
		border: 1px solid #E5E5E5;
		border-radius: 8px;
		font-size: 14px;
	}
	
	.price-separator {
		color: #999999;
	}
}

.category-list {
	display: flex;
	flex-wrap: wrap;
	gap: 10px;
}

.category-item {
	padding: 8px 16px;
	border: 1px solid #E5E5E5;
	border-radius: 20px;
	background: #F8F9FA;
	
	&.active {
		background: var(--primary-color);
		border-color: var(--primary-color);
		
		.category-name {
			color: #FFFFFF;
		}
	}
	
	.category-name {
		font-size: 14px;
		color: #333333;
	}
}

.modal-footer {
	display: flex;
	padding: 20px;
	gap: 15px;
	
	.reset-btn,
	.confirm-btn {
		flex: 1;
		height: 44px;
		border-radius: 8px;
		font-size: 16px;
		border: none;
	}
	
	.reset-btn {
		background: #F8F9FA;
		color: #666666;
	}
	
	.confirm-btn {
		background: var(--primary-color);
		color: #FFFFFF;
	}
}

.sort-content {
	background: #FFFFFF;
	border-radius: 12px 12px 0 0;
	width: 100%;
}

.sort-option {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px;
	border-bottom: 1px solid #F0F0F0;
	
	&:last-child {
		border-bottom: none;
	}
	
	&.active {
		.sort-label {
			color: var(--primary-color);
		}
	}
	
	.sort-label {
		font-size: 16px;
		color: #333333;
	}
	
	.sort-check {
		font-size: 16px;
		color: var(--primary-color);
	}
}
</style>